﻿using CRL.Core.Extension;
using CRL.Core.Remoting.WorkConsole;
using System;
using System.Collections.Generic;
using System.Text;

namespace CRL.RedisProvider
{
    public class RedisWorkManageClient : IWorkManageClient
    {
        public Action<string> OnPauseWork { get; set; }
        public Action<string> OnResumeWork { get; set; }

        static IRedisClient redisClient;
        IRedisClient getRedisClient()
        {
            if (redisClient == null)
            {
                redisClient = RedisClientFactory.GetCient();
            }
            return redisClient;
        }
        int lastDay = DateTime.Now.Day;
        public void UpdateTaskStatus(string workName, TaskStatus status, long elMs, string error)
        {
            var client = getRedisClient();
            var work = client.HGet<WorkDetail>("QuartzWorks", workName);
            if (work == null)
            {
                return;
                work = new WorkDetail { WorkName = workName, WorkStatus = WorkStatus.Runing };
            }
            work.TaskStatus = status;
            work.LastElMs = elMs;
            work.LastError = error;
            work.LastWorkTime = DateTime.Now;
            work.HeartTime = DateTime.Now;
            if (elMs > 0)
            {
                work.Times += 1;
            }
            if (lastDay != DateTime.Now.Day)
            {
                work.Times = 1;
                lastDay = DateTime.Now.Day;
            }
            client.HSet("QuartzWorks", workName, work);
        }

        public void InitWork(WorkDetail work)
        {
            work.MachineName = Environment.MachineName;
            var client = getRedisClient();
            client.HSet("QuartzWorks", work.WorkName, work);
        }

        public void RemoveWork(string workName)
        {
            var client = getRedisClient();
            client.HRemove("QuartzWorks", workName);
        }

        public void StartMonitor()
        {
            var client = getRedisClient();
            client.Subscribe(typeof(WorkCommand).Name, (msg, channel) =>
            {
                var b = msg.ToObject<WorkCommand>();
                if (b.Command == Command.Pause)
                {
                    OnPauseWork(b.WorkName);
                }
                else if (b.Command == Command.Resume)
                {
                    OnResumeWork(b.WorkName);
                }
            });
        }

        public void UpdateWorkStatus(string workName, WorkStatus status)
        {
            var client = getRedisClient();
            var work = client.HGet<WorkDetail>("QuartzWorks", workName);
            if (work == null)
            {
                return;
                work = new WorkDetail { WorkName = workName };
            }
            work.WorkStatus = status;
            client.HSet("QuartzWorks", workName, work);
        }
    }
}
